//
//  SpotSelectCollectionView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/5.
//

import UIKit

class SpotSelectCollectionView: UIView, UITextFieldDelegate {
    var collectionValue:String!
    var maximumAmount:String = ""
    var minimumAmount:String = ""

    typealias SpotCollectionValueBlock = (_ collectionValue:String) -> Void
    var spotCollectionValueBlock : SpotCollectionValueBlock!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        self.setUI()
        self.getData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setUI() {
        self.addSubview(self.mainView)
        self.mainView.addSubview(self.cencelBtn)
        self.mainView.addSubview(self.titleLab)
        self.mainView.addSubview(self.textField)
        self.mainView.addSubview(self.unitLab)
        self.mainView.addSubview(self.lineView)
        self.mainView.addSubview(self.confirmBtn)
        self.mainView.snp.makeConstraints { (make) in
            make.left.equalTo(self.snp.left).offset(0);
            make.right.equalTo(self.snp.right).offset(0);
            make.bottom.equalTo(self.snp.bottom).offset(15);
            make.height.equalTo(215 + Constants.xSafeBottomHeight);
        }
        self.cencelBtn.snp.makeConstraints { (make) in
            make.height.equalTo(40);
            make.width.equalTo(40);
            make.top.equalTo(self.mainView.snp.top).offset(15);
            make.right.equalTo(self.mainView.snp.right).offset(-15);
        }
        self.titleLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(15);
            make.top.equalTo(self.mainView.snp.top).offset(15);
        }
        self.lineView.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(20);
            make.right.equalTo(self.mainView.snp.right).offset(-40);
            make.top.equalTo(self.titleLab.snp.bottom).offset(68);
            make.height.equalTo(1);
        }
        self.unitLab.snp.makeConstraints { (make) in
            make.right.equalTo(self.snp.right).offset(-20);
            make.top.equalTo(self.titleLab.snp.bottom).offset(0);
            make.bottom.equalTo(self.lineView.snp.top).offset(0);
        }
        self.textField.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(20);
            make.top.equalTo(self.titleLab.snp.bottom).offset(0);
            make.right.equalTo(self.unitLab.snp.left).offset(-15);
            make.bottom.equalTo(self.lineView.snp.top).offset(0);
        }
        self.confirmBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.mainView.snp.left).offset(60);
            make.right.equalTo(self.mainView.snp.right).offset(-60);
            make.bottom.equalTo(self.mainView.snp.bottom).offset(-(Constants.xSafeBottomHeight == 0 ? 23 : Constants.xSafeBottomHeight + 23));
            make.height.equalTo(40);
        }
        
        self.setValueUI()
    }
    func getData() {
        if maximumAmount.count  <= 0 {
            Constants.window?.makeToastActivity(.center)
            HttpService.sharedHttpService().getCollectionScopeSuccess { (json, state, error) in
                Constants.window?.hideToast()
                if state {
                    self.maximumAmount = json["data"]["maximumAmount"].description
                    self.minimumAmount = json["data"]["minimumAmount"].description
                    if self.maximumAmount.count <= 0 || self.minimumAmount.count <= 0 {
                        self.maximumAmount = "1000000"
                        self.minimumAmount = "1"
                    }
                }
                Constants.window?.makeToast(error)
                self.maximumAmount = "1000000"
                self.minimumAmount = "1"
            }
        }
    }
    func setValueUI()  {
        titleLab.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_collectionDelivery)
        textField.text = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_hint_collectionDelivery)
        confirmBtn.setTitle(ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_confirm), for: .normal)
    }
    
    func setCollectionValue(collectionValue:String)  {
        self.collectionValue = collectionValue
        textField.text = collectionValue
    }
    
    @objc func clickCancelBtn()  {
        self.removeFromSuperview()
    }
    @objc func clickConfirmBtn()  {
        if self.textField.text?.count ?? 0 <= 0 {
            if (spotCollectionValueBlock != nil) {
                spotCollectionValueBlock(textField.text ?? "")
            }
            self.removeFromSuperview()
            return
        }
        if textField.text ?? "" > maximumAmount || textField.text ?? "" < minimumAmount {
            var str:NSString = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_import_integer) as NSString
            str = str.replacingOccurrences(of: "minimumAmount", with: minimumAmount) as NSString
            str = str.replacingOccurrences(of: "maximumAmount", with: maximumAmount) as NSString
            Constants.window?.makeToast(str as String)
            return
        }
        if (spotCollectionValueBlock != nil) {
            spotCollectionValueBlock(textField.text ?? "")
        }
        self.removeFromSuperview()
    }
    @objc func textFieldChange()  {
        confirmBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        confirmBtn.setTitleColor(UIColor.init(hexString: "#000000"), for: .normal)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let cs:CharacterSet = CharacterSet.init(charactersIn: "0123456789.").inverted
        let filtered = string.components(separatedBy: cs).joined(separator: "")
        if string != filtered {
            return false
        }
        if string == "" {
            self.perform(#selector(textFieldChange), with: self, afterDelay: 0.3)
            return true
        }
        
        if (textField.text! as NSString).range(of: ".").location != NSNotFound {
            if string == "." {
                return false
            }
           let index = (textField.text! as NSString).range(of: ".").location
            if textField.text?.count ?? 0 - index > 2 {
                return false
            }
        } else {
            if textField.text?.count ?? 0 > 0 {
                if textField.text?.prefix(1) == "0" {
                    if string != "." {
                        return false
                    }
                }
            } else {
                if string == "." {
                    return false
                }
            }
        }
        let totalStr = textField.text ?? "" + string
        if totalStr > self.maximumAmount {
            var str:NSString = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_import_integer) as NSString
            str = str.replacingOccurrences(of: "minimumAmount", with: self.minimumAmount) as NSString
            str = str.replacingOccurrences(of: "maximumAmount", with: self.maximumAmount) as NSString
            Constants.window?.makeToast(str as String)
            return false
        }
        self.perform(#selector(textFieldChange), with: self, afterDelay: 0.3)
        return true
        
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.endEditing(true)
    }
    @objc func keyboardShow(notification:Notification)  {
        UIView.animate(withDuration: 1) {
            self.mainView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.snp.bottom).offset(-250);
            }
        }
    }
    
    @objc func keyboardHide(notification:Notification)  {
        UIView.animate(withDuration: 1) {
            self.mainView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.snp.bottom).offset(0)
            }
        }
    }
    lazy var mainView: UIView = {
        let mainView = UIView()
        mainView.backgroundColor = UIColor.white
        mainView.layer.masksToBounds = true
        mainView.layer.cornerRadius = 15
        return mainView
    }()
    lazy var cencelBtn: UIButton = {
        let cencelBtn = UIButton.init(type: .custom)
        cencelBtn.setImage(UIImage.init(named: "login_cancel"), for: .normal)
        cencelBtn.addTarget(self, action: #selector(clickCancelBtn), for: .touchUpInside)
        return cencelBtn
    }()
    lazy var titleLab: UILabel = {
        let titleLab = UILabel.init()
        titleLab.font = UIFont.boldSystemFont(ofSize: 17)
        titleLab.textColor = UIColor.init(hexString: "#4C4C4C")
        return titleLab
    }()
    lazy var unitLab: UILabel = {
        let unitLab = UILabel.init()
        unitLab.font = UIFont.systemFont(ofSize: 17)
        unitLab.text = "MMK"
        unitLab.textColor = UIColor.init(hexString: "#000000")
        return unitLab
    }()
    lazy var textField: UITextField = {
        let textField = UITextField.init()
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.textColor = UIColor.init(hexString: "#000000")
        textField.delegate = self
        textField.keyboardType = UIKeyboardType.numberPad
        return textField
    }()
    lazy var lineView: UIView = {
        let lineView = UIView.init()
        lineView.backgroundColor = UIColor.init(hexString: "#CACACA")
        return lineView
    }()
    lazy var confirmBtn: UIButton = {
        let confirmBtn = UIButton.init(type: .custom)
        confirmBtn.addTarget(self, action: #selector(clickConfirmBtn), for: .touchUpInside)
        confirmBtn.layer.masksToBounds = true
        confirmBtn.layer.cornerRadius = 20
        confirmBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        confirmBtn.backgroundColor = UIColor.init(hexString: "#FFD10A")
        confirmBtn.setTitleColor(UIColor.init(hexString: "#000000"), for: .normal)
        confirmBtn.isSelected = true
        return confirmBtn
    }()
}
